//
//  MainViewController.m
//  CrazyRiddle
//
//  Created by mac on 2017/9/19.
//  Copyright © 2017年 上海LOL信息技术服务有限公司. All rights reserved.
//

#import "MainViewController.h"

#define CP_Words_Container_Width 300
#define CP_Words_Container_Margin 5
#define CP_Words_Container_Colomes 8
#define CP_Words_Container_Rows 3
#define CP_Word_Cell_Margin 4
#define CP_Word_Cell_Size (CP_Words_Container_Width-CP_Words_Container_Margin*2-CP_Word_Cell_Margin*(CP_Words_Container_Colomes-1))/CP_Words_Container_Colomes
#define CP_Scale_Factor 1.2
#define CP_Words_Container_Height  CP_Words_Container_Margin*2 + CP_Word_Cell_Margin*(CP_Words_Container_Rows-1)+CP_Word_Cell_Size*CP_Words_Container_Rows

#define CP_WordButton_Tag 1000
#define CP_AnswerButton_Tag 2000

#define degree(x) x * M_PI / 180


const static NSString *_globalWordsString = @"寿 弄 麦 形 进 戒 吞 远 违 运 扶 抚 坛 技 坏 扰 拒 找 批 扯 址 走 抄 坝 贡 攻 赤 折 抓 扮 抢 孝 均 抛 投 坟 抗 坑 坊 抖 护 壳 志 扭 块 声 把 报 却 劫 芽 花 芹 芬 苍 芳 严 芦 劳 克 苏 杆 杠 杜 材 村 杏 极 李 杨 求 更 束 豆 两 丽 医 辰 励 否 还 歼 来 连 步 坚 旱 盯 呈 时 吴 助 县 里 呆 园 旷 围 呀 吨 足 邮 男 困 吵 串 员 听 吩 吹 呜 吧 吼 别 岗 帐 财 针 钉 告 我 乱 利 秃 秀 私 每 兵 估 体 何 但 伸 作 伯 伶 佣 低 你 住 位 伴 身 皂 佛 近 彻 役 返 余 希 坐 谷 妥 含 邻 岔 肝 肚 肠 龟 免 狂 犹 角 删 条 卵 岛 迎 饭 饮 系 言 冻 状 亩 况 床 库 疗 应 冷 这 序 辛 弃 冶 忘 闲 间 闷 判 灶 灿 弟 汪 沙 汽 沃 泛 沟 没 沈 沉 怀 忧 快 完 宋 宏 牢 究 穷 灾 良 证 启 评 补 初 社 识 诉 诊 词 译 君 灵 即 层 尿 尾 迟 局 改 张 忌 际 陆 阿 陈 阻 附 妙 妖 妨 努 忍 劲 鸡 驱 纯 纱 纳 纲 驳 纵 纷 纸 纹 纺 驴 纽";



@interface MainViewController ()

@property (nonatomic,strong) UIImageView *picImageView;
@property (nonatomic,strong) UIButton *answerButtonOne;
@property (nonatomic,strong) UIButton *answerButtonTwo;
@property (nonatomic,strong) UIButton *answerButtonThree;
@property (nonatomic,strong) UIButton *answerButtonFour;

@property (nonatomic,strong) NSArray *globalWordsArray; //所有汉字
@property (nonatomic,strong) NSMutableArray *currentAnswerArray; // 答案
@property (nonatomic,strong) NSArray *currentWordsArray;//24个包含答案的数组

@property (nonatomic,strong) NSMutableDictionary *maps; // 用于记录点击的哪一个文字

@property (nonatomic,assign) BOOL isCorrect;  // 答案是否正确



@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self p_setupUI];
    [self p_setupCurrentWordsArray];
    [self p_setupWordContainerView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark --- 答案Action
-(void)answerButtonClick:(UIButton *)sender{
    // 获得 wordbutton  并让wordbutton显示
    NSString * wordButtonTag = self.maps[[NSString stringWithFormat:@"%ld",(long)(sender.tag - CP_AnswerButton_Tag)]];
    UIButton *wordButton = [self.view viewWithTag:wordButtonTag.intValue];
    wordButton.hidden = NO;

    // 清空答案的按钮
    [sender setTitle:@"" forState:UIControlStateNormal];

}

-(void)wordButtonSelected:(UIButton *)sender{
    
    for (int i = 0; i<4; i++) {
        UIButton *answerButton = (UIButton *)[self.view viewWithTag:CP_AnswerButton_Tag + i];
        if ([answerButton.currentTitle isEqualToString:@""] || answerButton.currentTitle == nil) {
            [answerButton setTitle:sender.currentTitle forState:UIControlStateNormal];
            sender.hidden = YES;
//            如{0:1,1:3,2:12,3:21}
            [self.maps setValue:[NSString stringWithFormat:@"%.0ld",(long)sender.tag] forKey:[NSString stringWithFormat:@"%d",i]];
            break;
        }
    }
    

    
    if (self.maps.allValues.count == 4) {
        // 说明已经填写完成
        // 取值判断对错
        NSMutableArray *answerTempArray = [NSMutableArray array];
        for (int i = 0; i<4; i++) {
            NSString *tagstring = self.maps[[NSString stringWithFormat:@"%d",i]];
            NSInteger tag = tagstring.intValue - CP_WordButton_Tag;
            [answerTempArray addObject:self.currentWordsArray[tag]];
        }

        if ([self.currentAnswerArray isEqualToArray:answerTempArray]) {
            NSLog(@"正确");
            self.isCorrect = YES;
            [WCAlertView showAlertWithTitle:@"正确" message:nil customizationBlock:nil completionBlock:nil cancelButtonTitle:@"确定" otherButtonTitles:@"下一题", nil];
        }else{
            NSLog(@"不正确");
            self.isCorrect = NO;
            [self p_checkWrong];
        }
    }
    
    
}

#pragma mark --- privateMethod
-(void)p_checkWrong{
    for (int i=0; i<4; i++) {
        UIButton *btn = (UIButton *)[self.view viewWithTag:(i+CP_AnswerButton_Tag)];
        CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z" ];
        animation.duration = 0.25;
        animation.repeatCount = 4;
        float rand = (float)random();
        [animation setBeginTime:CACurrentMediaTime() + rand * .0000000001];
        NSMutableArray *values = [NSMutableArray array];
        [values addObject:[NSNumber numberWithFloat:degree(-4)]];
        [values addObject:[NSNumber numberWithFloat:degree(4)]];
        [values addObject:[NSNumber numberWithFloat:degree(-4)]];
        animation.values=values;
        [btn.layer addAnimation:animation forKey:nil];
        [UIView animateWithDuration:1 animations:^{
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        } completion:^(BOOL finished){
        }];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self p_clearAllWrongWords];
    });
}

// 清空错误答案数据
-(void)p_clearAllWrongWords{
    
    // 清空答案UI
    for (int i=0; i<4; i++) {
        UIButton *btn = (UIButton *)[self.view viewWithTag:(i+CP_AnswerButton_Tag)];
        [btn setTitle:@"" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    
    // 让隐藏的按钮显示
    for (int i = 0; i<4; i++) {
        NSString *tagstring = self.maps[[NSString stringWithFormat:@"%d",i]];
        UIButton *btn = (UIButton *)[self.view viewWithTag:tagstring.intValue];
        btn.hidden = NO;
    }
    
    // 清空字典
    [self.maps removeAllObjects];
 
}

#pragma mark --- setupUI
-(void)p_setupUI{
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIImageView *backImageView = [[UIImageView alloc]init];
    backImageView.image = [UIImage imageNamed:@"background.png"];
    [self.view addSubview:backImageView];
    [backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.picImageView = [[UIImageView alloc]init];
    self.picImageView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.picImageView];
    [self.picImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(30+64);
        make.width.mas_equalTo(216);
        make.height.mas_equalTo(155);
    }];
    
    CGFloat answerButtonWH = 44;
    CGFloat answerButtonMargin = 10;
    
    UIView *answerButtonView = [[UIView alloc]init];
    [self.view addSubview:answerButtonView];
    [answerButtonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(answerButtonWH);
        make.width.mas_equalTo(answerButtonWH*4+answerButtonMargin*3);
        make.top.equalTo(self.picImageView.mas_bottom).offset(50);
    }];
    
    [answerButtonView addSubview:self.answerButtonOne];
    [self.answerButtonOne mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(answerButtonView);
        make.width.mas_equalTo(answerButtonWH);
    }];
    [answerButtonView addSubview:self.answerButtonTwo];
    [self.answerButtonTwo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(answerButtonView);
        make.width.mas_equalTo(answerButtonWH);
        make.left.equalTo(answerButtonView).offset(answerButtonWH+answerButtonMargin);
    }];
    [answerButtonView addSubview:self.answerButtonThree];
    [self.answerButtonThree mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(answerButtonView);
        make.width.mas_equalTo(answerButtonWH);
        make.left.equalTo(answerButtonView).offset(answerButtonWH*2+answerButtonMargin*2);
    }];
    [answerButtonView addSubview:self.answerButtonFour];
    [self.answerButtonFour mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(answerButtonView);
        make.width.mas_equalTo(answerButtonWH);
        make.left.equalTo(answerButtonView).offset(answerButtonWH*3+answerButtonMargin*3);
    }];
    
}

-(void)p_setupCurrentWordsArray{
    // 答案数组
    NSString *file = [[NSBundle mainBundle] pathForResource:@"question" ofType:@"plist"];
    NSArray * array = [NSArray arrayWithContentsOfFile:file];
    if([array[0] isKindOfClass:[NSDictionary class]]){
        NSString *answerString = [array[0] objectForKey:@"answer"];
        self.currentAnswerArray = [NSMutableArray array];
        for (int i = 0; i<answerString.length; i++) {
            [self.currentAnswerArray addObject:[answerString substringWithRange:NSMakeRange(i, 1)]];
        }
    }
    
    // 再随机取20个汉字
    NSMutableArray *tempArray = [NSMutableArray array];
    for (int i = 0; i<20; i++) {
        int x = arc4random() % self.globalWordsArray.count;
        [tempArray addObject:self.globalWordsArray[x]];
    }
    
    // 加上4个答案
    for (int i = 0; i<4; i++) {
        [tempArray addObject:self.currentAnswerArray[i]];
    }
    
    // 随机数组
    self.currentWordsArray = [tempArray copy];
    self.currentWordsArray = [self.currentWordsArray sortedArrayUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
        int seed = arc4random_uniform(2);
        if (seed) {
            return [str1 compare:str2];
        } else {
            return [str2 compare:str1];
        }
    }];
}

-(void)p_setupWordContainerView{
    UIView *backWordView = [[UIView alloc]init];
    [self.view addSubview:backWordView];
    [backWordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.answerButtonOne.mas_bottom).offset(50);
        make.width.mas_equalTo(CP_Words_Container_Width-CP_Words_Container_Margin);
        make.height.mas_equalTo(CP_Words_Container_Height);
    }];
    
    for (int i = 0; i<self.currentWordsArray.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundImage:[UIImage imageNamed:@"word.png"] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"word_press.png"] forState:UIControlStateHighlighted];
        btn.tag = CP_WordButton_Tag + i;
        [btn setTitle:self.currentWordsArray[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(wordButtonSelected:) forControlEvents:UIControlEventTouchUpInside];
        CGFloat x = i%CP_Words_Container_Colomes*(CP_Word_Cell_Size+CP_Word_Cell_Margin) +CP_Words_Container_Margin;
        CGFloat y = (i/CP_Words_Container_Colomes)*(CP_Word_Cell_Size+CP_Word_Cell_Margin) + CP_Words_Container_Margin;
        btn.frame = CGRectMake(x, y, CP_Word_Cell_Size, CP_Word_Cell_Size);
        [backWordView addSubview:btn];
    }
 
}

#pragma mark --- set get
-(UIButton *)answerButtonOne{
    if (_answerButtonOne == nil) {
        _answerButtonOne = [UIButton buttonWithType:UIButtonTypeCustom];
        [_answerButtonOne setBackgroundImage:[UIImage imageNamed:@"answer"] forState:UIControlStateNormal];
        [_answerButtonOne addTarget:self action:@selector(answerButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        _answerButtonOne.tag = CP_AnswerButton_Tag;
    }
    return _answerButtonOne;
}

-(UIButton *)answerButtonTwo{
    if (_answerButtonTwo == nil) {
        _answerButtonTwo = [UIButton buttonWithType:UIButtonTypeCustom];
        [_answerButtonTwo setBackgroundImage:[UIImage imageNamed:@"answer"] forState:UIControlStateNormal];
        [_answerButtonTwo addTarget:self action:@selector(answerButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        _answerButtonTwo.tag = CP_AnswerButton_Tag+1;

    }
    return _answerButtonTwo;
}

-(UIButton *)answerButtonThree{
    if (_answerButtonThree == nil) {
        _answerButtonThree = [UIButton buttonWithType:UIButtonTypeCustom];
        [_answerButtonThree setBackgroundImage:[UIImage imageNamed:@"answer"] forState:UIControlStateNormal];
        [_answerButtonThree addTarget:self action:@selector(answerButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        _answerButtonThree.tag = CP_AnswerButton_Tag+2;

    }
    return _answerButtonThree;
}

-(UIButton *)answerButtonFour{
    if (_answerButtonFour == nil) {
        _answerButtonFour = [UIButton buttonWithType:UIButtonTypeCustom];
        [_answerButtonFour setBackgroundImage:[UIImage imageNamed:@"answer"] forState:UIControlStateNormal];
        [_answerButtonFour addTarget:self action:@selector(answerButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        _answerButtonFour.tag = CP_AnswerButton_Tag+3;

    }
    return _answerButtonFour;
}

-(NSArray *)globalWordsArray{
    if (_globalWordsArray  == nil) {
        _globalWordsArray = [NSArray array];
        _globalWordsArray = [_globalWordsString componentsSeparatedByString:@" "];
    }
    return _globalWordsArray;
}

-(NSMutableDictionary *)maps{
    if (_maps == nil) {
        _maps = [NSMutableDictionary dictionary];
    }
    return _maps;
}







@end






